﻿using System;
using System.Collections.Generic;
using SaleManagement.Domains;
using SaleManagement.Services;
using SaleManagement.Web.App_Code;
using Library.Encryption;
using DevExpress.Web;

namespace HPS.TTCS.Web.Pages
{
  public partial class UserFunctions : BasePage
  {
    #region Private Members
    internal override int RequiredPermission
    {
      get
      {
        return -1;
      }
    }

    private string _innerError = string.Empty;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack && !IsCallback)
      {
        LoadUserList();
        LoadFunctionList();
        cbxStatus.Value = "A";
      }
    }

    protected void gvUserList_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      string para = e.Parameters;
      if (para == "Save")
      {
        _innerError = SaveUserFunction();
        LoadUserList();
      }
      else if (para == "ResetPass")
      {
        _innerError = ResetPass();
      }

    }

    protected void gvUserList_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = _innerError;
    }

    protected void gvFunctions_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      string userName = e.Parameters;
      TList<UserFunction> listUserFunction = new UserFunctionService().GetByUsername(userName);
      gvFunctions.Selection.UnselectAll();
      foreach (UserFunction userFunc in listUserFunction)
      {
        gvFunctions.Selection.SetSelectionByKey(userFunc.FunctionId, true);
      }
    }

    protected void gvUserList_PageIndexChanged(object sender, EventArgs e)
    {
      LoadUserList();
    }
    #endregion

    #region Helpers
    private void LoadUserList()
    {
      int total = 0;
      TList<User> listUser = new TList<User>();
      listUser = new UserService().GetPaged(string.Format("Username <> 'admin'"), "UserName", 0, int.MaxValue, out total);
      gvUserList.DataSource = listUser;
      gvUserList.DataBind();
    }

    private void LoadFunctionList()
    {
      TList<Function> listFunction = new FunctionService().GetAll();
      gvFunctions.DataSource = listFunction;
      gvFunctions.DataBind();
    }

    private string SaveUserFunction()
    {
      #region Check parameter
      if (Utilities.SafeString(txtUsername.Text) == null)
      {
        return "Tên đăng nhập không được để trống";
      }
      #endregion
      #region Save into DB
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          #region Save User
          bool isNew = false;
          User user = new User();
          string pass = string.Empty;
          UserService userService = new UserService();
          if (!string.IsNullOrEmpty(hfUser.Value.Trim()))
          {
            user = userService.GetByUsername(Utilities.SafeString(hfUser.Value));
          }
          else
          {
            isNew = true;
            string username = Utilities.SafeString(txtUsername.Text);
            if (userService.GetByUsername(username) != null)
            {
              return "Tên đăng nhập đã tồn tại";
            }
            user.Username = username;
            user.Creator = "admin";
            user.CreatedDate = DateTime.Now;
            pass = GenPass();
            user.Password = MD5.Encrypt(pass);
          }
          user.FullName = Utilities.SafeString(txtFullname.Text);
          user.Email = Utilities.SafeString(txtEmail.Text);
          user.Phone = Utilities.SafeString(txtPhone.Text);
          user.Status = cbxStatus.Value.ToString();
          userService.Save(user);

          #endregion
          #region Save Functions
          List<int> listSelectId = new List<int>();
          List<object> listSelectFunction = (List<object>)gvFunctions.GetSelectedFieldValues("Id");
          foreach (object obj in listSelectFunction)
          {
            int functionId = (int)obj;
            listSelectId.Add(functionId);
          }
          for (int i = 0; i < gvFunctions.VisibleRowCount; i++)
          {
            int functionId = (int)gvFunctions.GetRowValues(i, "Id");
            UserFunctionService userFunctionService = new UserFunctionService();

            UserFunction userFunction = userFunctionService.GetByUsernameFunctionId(user.Username, functionId);
            if (!listSelectId.Contains(functionId))
            {
              if (userFunction != null)
              {
                userFunctionService.Delete(userFunction);
              }
            }
            else
            {
              if (userFunction == null)
              {
                userFunction = new UserFunction();
                userFunction.Username = user.Username;
                userFunction.FunctionId = functionId;
                userFunctionService.Save(userFunction);
              }
            }
          }
          #endregion
          ConnectionScope.Complete();
          string returnMessgage = "S|Save|Cập nhật thành công.";
          if (isNew)
          {
            returnMessgage += " Password là: " + pass;
          }
          return returnMessgage;

        }
      }
      catch (Exception ex)
      {
        WriteLog("Save User Functions", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
      #endregion
    }

    private string ResetPass()
    {
      try
      {
        if (Utilities.SafeString(hfUser.Value) != null)
        {
          string pass = GenPass();
          string userName = Utilities.SafeString(hfUser.Value);
          UserService userService = new UserService();
          User user = userService.GetByUsername(userName);
          if (user != null)
          {
            user.Password = MD5.Encrypt(pass);
            userService.Save(user);
          }
          else
          {
            return "Không tìm thấy người dùng tương ứng";
          }
          string returnMessgage = "S|Save|Cập nhật thành công.Password mới là : " + pass;
          return returnMessgage;
        }
        return "S";
      }
      catch (Exception ex)
      {
        WriteLog("Reset Pass", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }

    private string GenPass()
    {
      Random rand = new Random();
      return rand.Next(0, 999999).ToString();
    }
    #endregion
  }
}
